#include <memory>
#include <iostream>
using std::cout;
using std::endl;
using std::unique_ptr;
using std::string;
using std::shared_ptr;

//通过函数对象实现文件指针的托管
//这里采用了删除器的方式来完成
struct Myfpcloser
{
    void operator()(FILE * fp)
    {
        if(fp) {
            fclose(fp);
            cout << " >> fclose(fp)" << endl;
        }
    }
};

void test0()
{
    unique_ptr<FILE, Myfpcloser> up(fopen("test.txt", "a+"));
    cout << "sizeof(up):" << sizeof(up) << endl;
    string msg("this is a test\n");
    fwrite(msg.c_str(), 1, msg.size(), up.get());
}

void test1()
{
    Myfpcloser myfpcloser;
    FILE * fp = fopen("test.txt", "a+");
    myfpcloser(fp);
}

void test2()
{
    Myfpcloser myfp;
    //shared_ptr<FILE> sp(fopen("test.txt", "a+"), Myfpcloser());
    shared_ptr<FILE> sp(fopen("test.txt", "a+"), myfp);
    cout << "sizeof(sp):" << sizeof(sp) << endl;
    string msg("this is a shared_ptr test\n");
    fwrite(msg.c_str(), 1, msg.size(), sp.get());
}


int main()
{
    test0();
    /* test1(); */
    test2();
    return 0;
}

